package com.ice.work.moment.tencent.service.impl;

import com.honeybee.cloud.framework.base.exception.business.BaseBizException;
import com.honeybee.cloud.framework.common.enums.DataStatusEnum;
import com.ice.work.moment.tencent.dao.user.UserRepository;
import com.ice.work.moment.tencent.facade.dto.UserDTO;
import com.ice.work.moment.tencent.facade.mapper.UserConvertMapper;
import com.ice.work.moment.tencent.facade.model.User;
import com.ice.work.moment.tencent.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @Description
 * @Author DELL
 * @Create 2019-07-04
 * @Since 1.0.0
 */
@Service
public class UserService implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public Boolean addUser(User user) throws BaseBizException {
        User exists = userRepository.findByOpenIdAndDataStatus(user.getOpenId(), DataStatusEnum.VALID.key);
        if (Objects.nonNull(exists)) {
            user.setId(exists.getId());
        }else {
            user.setDataStatus(DataStatusEnum.VALID.key);
            user.setCreateAt(new Date());
        }
        return userRepository.saveOrUpdate(user);
    }

    @Override
    public UserDTO findUserByOpenId(String openId) throws BaseBizException {
        User user = userRepository.findByOpenIdAndDataStatus(openId, DataStatusEnum.VALID.key);
        return UserConvertMapper.INSTANCE.toDTO(user);
    }
}
